package com.yjhb.android.sbz.tool;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityOptionsCompat;

import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.Conf;
import com.yjhb.android.sbz.DataConf;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.ChatActivity;
import com.yjhb.android.sbz.activity.LoginActivity;
import com.yjhb.android.sbz.activity.RechargeActivity;
import com.yjhb.android.sbz.activity.RedPackDetailActivity;
import com.yjhb.android.sbz.activity.SendRedPackActivity;
import com.yjhb.android.sbz.activity.TaskCheckListActivity;
import com.yjhb.android.sbz.activity.TaskDetailsActivity;
import com.yjhb.android.sbz.activity.TimerListActivity;
import com.yjhb.android.sbz.activity.UserInfoActivity;
import com.yjhb.android.sbz.activity.WebViewActivity;
import com.yjhb.android.sbz.activity.WithdrawalActivity;
import com.yjhb.android.sbz.activity.publishtask.PublishActivity;
import com.yjhb.android.sbz.activity.rule.RuleOrderActivity;
import com.yjhb.android.sbz.activity.rule.RulePublishActivity;
import com.yjhb.android.sbz.activity.rule.RulePunishmentActivity;
import com.yjhb.android.sbz.activity.rule.RuleReportActivity;
import com.yjhb.android.sbz.activity.rule.RuleReputationActivity;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.entity.ManagerTask;
import com.yjhb.android.sbz.entity.RedPackDetails;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.v2.entity.VipConfig;
import com.jojo.android.zxlib.entity.Result;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.TrustAllCerts;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxDataTool;
import com.jojo.android.zxlib.tool.ZxEncodeTool;
import com.jojo.android.zxlib.tool.ZxEncryptTool;
import com.jojo.android.zxlib.tool.ZxFileTool;
import com.jojo.android.zxlib.tool.ZxImageTool;
import com.jojo.android.zxlib.tool.ZxImageUpload;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxTimeTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.tool.ZxTool;
import com.jojo.android.zxlib.view.PhotoActivity;
import com.king.zxing.util.CodeUtils;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAction;
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAdapter;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建者 zx
 * 创建时间 2020/11/24 13:05
 */
public class Tool {
    private final String TAG = "CommonTool";

    public static final int CATEGORY_ID_DOWNLOAD = 1000;
    public static final int CATEGORY_ID_REGISTER = 1001;
    public static final int CATEGORY_ID_BIND = 1002;
    public static final int CATEGORY_ID_EC = 1003;
    public static final int CATEGORY_ID_SE = 1004;

    public static final int CATEGORY_ID_ATTEN = 2000;
    public static final int CATEGORY_ID_VOTE = 2001;
    public static final int CATEGORY_ID_BARGAIN = 2002;
    public static final int CATEGORY_ID_FORWARD = 2003;
    public static final int CATEGORY_ID_BOOST = 2004;

    public static final int CATEGORY_ID_OTHER = 3000;

    /**
     * 应用试玩
     */
    public static final int CATEGORY_ID_APP_APPLY = 1005;
    /**
     * 新-账号注册
     */
    public static final int CATEGORY_ID_REGISTER_NEW = 2005;
    /**
     * 砍价助力
     */
    public static final int CATEGORY_ID_BARGAIN_BOOST = 2006;
    /**
     * 关注投票
     */
    public static final int CATEGORY_ID_ATTEN_VOTE = 2007;

    /**
     * 登录检测，如果没有登录就跳转套登陆页
     *
     * @param context
     * @return
     */
    public static boolean checkLogin(Context context) {
        if (App.userInfo == null) {
            ZxToast.showINFOBottomToast("请先登录。");
            ZxActivityTool.skipActivity(context, LoginActivity.class);
            return false;
        }
        return true;
    }


    /**
     * 返回我的会员信息
     *
     * @return
     */
    public static VipConfig getMyVipInfo() {
        Object object = Global.getInstance().getCache("vipConfig");
        if (object != null) {
            return (VipConfig) object;
        }
        return null;
    }

    /**
     * 检测EditView内容是否为空
     *
     * @param editText
     * @return
     */
    public static boolean isEditEmpty(EditText editText) {
        if (editText == null) {
            return true;
        }
        if (editText.getText() == null)
            return true;
        if (editText.getText().toString().equals("")) {
            return true;
        }
        return false;
    }

    /**
     * 重输入框中获取文本
     *
     * @param editText
     * @return
     */
    public static String getText(EditText editText) {
        return getText(editText, null);
    }

    public static String getText(EditText editText, String defaultText) {
        if (!isEditEmpty(editText)) {
            return editText.getText().toString();
        }
        return defaultText;
    }

    /**
     * 将发布类型转化为id
     *
     * @return
     */
    public static int publishTypeTransformID(String type) {
        int categoryId = -1;
        Resources res = App.getInstance().getResources();
        if (type.equals(res.getString(R.string.task_type_download_app))) {
            categoryId = CATEGORY_ID_DOWNLOAD;
        } else if (type.equals(res.getString(R.string.task_type_register))) {
            categoryId = CATEGORY_ID_REGISTER_NEW;
        } else if (type.equals(res.getString(R.string.task_type_approve))) {
            categoryId = CATEGORY_ID_BIND;
        } else if (type.equals(res.getString(R.string.task_type_eCommerce))) {
            categoryId = CATEGORY_ID_EC;
        } else if (type.equals(res.getString(R.string.task_type_securities))) {
            categoryId = CATEGORY_ID_SE;
        } else if (type.equals(res.getString(R.string.task_type_follow))) {
            categoryId = CATEGORY_ID_ATTEN;
        } else if (type.equals(res.getString(R.string.task_type_vote))) {
            categoryId = CATEGORY_ID_VOTE;
        } else if (type.equals(res.getString(R.string.task_type_bargain))) {
            categoryId = CATEGORY_ID_BARGAIN;
        } else if (type.equals(res.getString(R.string.task_type_forward))) {
            categoryId = CATEGORY_ID_FORWARD;
        } else if (type.equals(res.getString(R.string.task_type_help))) {
            categoryId = CATEGORY_ID_BOOST;
        } else if (type.equals(res.getString(R.string.task_type_other))) {
            categoryId = CATEGORY_ID_OTHER;
        } else if (type.equals(res.getString(R.string.task_type_app_apply))) {
            categoryId = CATEGORY_ID_APP_APPLY;
        } else if (type.equals(res.getString(R.string.task_type_bargain_help))) {
            categoryId = CATEGORY_ID_BARGAIN_BOOST;
        } else if (type.equals(res.getString(R.string.task_type_follow_vote))) {
            categoryId = CATEGORY_ID_ATTEN_VOTE;
        }
        return categoryId;
    }


    /**
     * 将类型ID转化为字符串
     *
     * @param categoryId
     * @return
     */
    public static String idTransformString(int categoryId) {
        String type = "";
        Resources res = App.getInstance().getResources();
        switch (categoryId) {
            case CATEGORY_ID_DOWNLOAD:
                type = res.getString(R.string.task_type_download_app);
                break;
            case CATEGORY_ID_REGISTER:
            case CATEGORY_ID_REGISTER_NEW:
                type = res.getString(R.string.task_type_register);
                break;
            case CATEGORY_ID_BIND:
                type = res.getString(R.string.task_type_approve);
                break;
            case CATEGORY_ID_EC:
                type = res.getString(R.string.task_type_eCommerce);
                break;
            case CATEGORY_ID_SE:
                type = res.getString(R.string.task_type_securities);
                break;
            case CATEGORY_ID_ATTEN:
                type = res.getString(R.string.task_type_follow);
                break;
            case CATEGORY_ID_VOTE:
                type = res.getString(R.string.task_type_vote);
                break;
            case CATEGORY_ID_BARGAIN:
                type = res.getString(R.string.task_type_bargain);
                break;
            case CATEGORY_ID_FORWARD:
                type = res.getString(R.string.task_type_forward);
                break;
            case CATEGORY_ID_BOOST:
                type = res.getString(R.string.task_type_help);
                break;
            case CATEGORY_ID_OTHER:
                type = res.getString(R.string.task_type_other);
                break;
            case CATEGORY_ID_APP_APPLY:
                type = res.getString(R.string.task_type_app_apply);
                break;
            case CATEGORY_ID_BARGAIN_BOOST:
                type = res.getString(R.string.task_type_bargain_help);
                break;
            case CATEGORY_ID_ATTEN_VOTE:
                type = res.getString(R.string.task_type_follow_vote);
                break;

        }
        return type;
    }


    /**
     * 校验发布金额
     *
     * @param categoryId
     * @return
     */

    public static boolean checkMoney(int categoryId, BigDecimal money) {
        return compare(money, getTaskMinMoney(categoryId));
    }

    /**
     * 根据分类ID查询最小金额
     *
     * @param categoryId
     * @return
     */
    public static BigDecimal getTaskMinMoney(int categoryId) {
        switch (categoryId) {
            case CATEGORY_ID_DOWNLOAD:
                return new BigDecimal(DataConf.CATEGORY_ID_DOWNLOAD);
            case CATEGORY_ID_REGISTER_NEW:
            case CATEGORY_ID_REGISTER:
                return new BigDecimal(DataConf.CATEGORY_ID_REGISTER);
            case CATEGORY_ID_BIND:
                return new BigDecimal(DataConf.CATEGORY_ID_BIND);
            case CATEGORY_ID_EC:
                return new BigDecimal(DataConf.CATEGORY_ID_EC);
            case CATEGORY_ID_SE:
                return new BigDecimal(DataConf.CATEGORY_ID_SE);
            case CATEGORY_ID_ATTEN:
            case CATEGORY_ID_VOTE:
            case CATEGORY_ID_BARGAIN:
            case CATEGORY_ID_FORWARD:
            case CATEGORY_ID_BOOST:
            case CATEGORY_ID_BARGAIN_BOOST:
            case CATEGORY_ID_ATTEN_VOTE:
                return new BigDecimal(DataConf.SIMPLE_TASK_PRICE);
            case CATEGORY_ID_OTHER:
                return new BigDecimal(DataConf.CATEGORY_ID_OTHER);
            case CATEGORY_ID_APP_APPLY:
                return new BigDecimal(DataConf.CATEGORY_ID_APP_APPLY);
        }
        return null;
    }

    /**
     * 校验发布任务数量
     *
     * @param categoryId
     * @return
     */

    public static boolean checkStock(int categoryId, int count) {
        return compare(count, getTaskMinStock(categoryId));
    }

    /**
     * 根据分类ID查询该任务最小发布数量
     *
     * @param categoryId
     * @return
     */
    public static int getTaskMinStock(int categoryId) {
        switch (categoryId) {
            case CATEGORY_ID_DOWNLOAD:
            case CATEGORY_ID_REGISTER:
            case CATEGORY_ID_BIND:
            case CATEGORY_ID_EC:
            case CATEGORY_ID_SE:
            case CATEGORY_ID_ATTEN:
            case CATEGORY_ID_VOTE:
            case CATEGORY_ID_BARGAIN:
            case CATEGORY_ID_FORWARD:
            case CATEGORY_ID_BOOST:
            case CATEGORY_ID_OTHER:
            case CATEGORY_ID_APP_APPLY:
            case CATEGORY_ID_REGISTER_NEW:
            case CATEGORY_ID_BARGAIN_BOOST:
            case CATEGORY_ID_ATTEN_VOTE:
                return 10;
        }
        return -1;
    }

    /**
     * 如果参数一大于参数二返回true
     *
     * @param money1
     * @param money2
     * @return
     */
    private static boolean compare(BigDecimal money1, BigDecimal money2) {
        if (money1 == null || money2 == null) return false;
        return money1.max(money2).equals(money1);
    }

    private static boolean compare(int num1, int num2) {
        return Math.max(num1, num2) == num1;
    }

    /**
     * 启动图片Activity(已动画缩放的方式)
     *
     * @param context
     * @param path
     * @param view
     */
    public static void startPhotoActivity(Context context, String path, View view) {
        Intent intent = new Intent(context, PhotoActivity.class);
        intent.putExtra("image", path);
        ActivityOptionsCompat compat = ActivityOptionsCompat.makeScaleUpAnimation(view, (int) view.getX(), (int) view.getY(),
                view.getWidth(), view.getHeight());
        context.startActivity(intent, compat.toBundle());
    }

    /**
     * 启动发布页
     *
     * @param context
     * @param editMode
     * @param addTask
     */
    public static void startPublishTaskActivity(Context context, int editMode, AddTask addTask) {
        //如果是重新发布任务，则克隆一个新的任务对象
        if (editMode == PublishActivity.MODE_REPUBLISH) {
            Task clone = new Task();
            Task task = addTask.getTask();
            clone.setTitle(task.getTitle());
            clone.setName(task.getName());
            clone.setMoney(task.getMoney());
            clone.setMaxStock(task.getMaxStock());
            clone.setCurrentStock(task.getCurrentStock());
            clone.setCategoryId(task.getCategoryId());
            clone.setRemark(task.getRemark());
            clone.setTotalMoney(task.getTotalMoney());
            clone.setDevice(task.getDevice());
            clone.setTaskTime(task.getTaskTime());
            clone.setAuditTime(task.getAuditTime());
            clone.setFetchType(task.getFetchType());
            clone.setFetchNum(task.getFetchNum());
            addTask.setTask(clone);
        }
        Intent intent = new Intent(context, PublishActivity.class);
        intent.putExtra("editMode", editMode);
        intent.putExtra("taskType", Tool.idTransformString(addTask.getTask().getCategoryId()));
        intent.putExtra("addTask", addTask);
        context.startActivity(intent);
    }

    /**
     * 以新增模式启动发布页
     *
     * @param context
     * @param taskType
     */
    public static void startPublishTaskAddModeActivity(Context context, String taskType) {
        Intent intent = new Intent(context, PublishActivity.class);
        intent.putExtra("editMode", PublishActivity.MODE_ADD);
        intent.putExtra("taskType", taskType);
        context.startActivity(intent);
    }

    /**
     * 以编辑模式打开任务详情页
     *
     * @param context
     * @param taskId
     */
    public static void startEditTaskDetailActivity(Context context, Integer taskId, ArrayList<Task> changeCache) {
        Intent intent = new Intent(context, TaskDetailsActivity.class);
        intent.putExtra("mode", TaskDetailsActivity.MODE_EDIT);
        intent.putExtra("taskId", "" + taskId);
        intent.putExtra("changeCache", changeCache);
        context.startActivity(intent);
    }

    public static void startEditTaskDetailActivity(Context context, Integer taskId) {
        startEditTaskDetailActivity(context, taskId, null);
    }

    /**
     * 以重新编辑模式打开任务详情页
     *
     * @param context
     * @param taskId
     */
    public static void startReeditTaskDetailActivity(Context context, Integer taskId, Integer orderId) {
        Intent intent = new Intent(context, TaskDetailsActivity.class);
        intent.putExtra("mode", TaskDetailsActivity.MODE_REEDIT);
        intent.putExtra("taskId", "" + taskId);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    /**
     * 以预览模式打开任务详情
     *
     * @param context
     * @param task
     * @param steps
     */
    public static void startPreviewTaskDetailActivity(Context context, Task task, ArrayList<TaskStep> steps) {
        Intent intent = new Intent(context, TaskDetailsActivity.class);
        intent.putExtra("mode", TaskDetailsActivity.MODE_PREVIEW);
        intent.putExtra("task", task);
        intent.putExtra("taskSteps", steps);
        context.startActivity(intent);
    }

    /**
     * 以预览模式打开任务详情
     *
     * @param context
     */
    public static void startPreviewTaskDetailActivity(Context context, Integer taskId) {
        Intent intent = new Intent(context, TaskDetailsActivity.class);
        intent.putExtra("mode", TaskDetailsActivity.MODE_READ);
        intent.putExtra("taskId", "" + taskId);
        context.startActivity(intent);
    }

    /**
     * 启动WebActivity
     *
     * @param context
     * @param url
     * @param title
     */
    public static void startWebActivity(Context context, String url, String title) {
        if (!url.startsWith("http")) {
            url += "http://" + url;
        }
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }


    /**
     * 跳转外部浏览器
     *
     * @param context
     * @param url
     */
    public static void startExternalWeb(Context context, String url) {
        try {
            if (!url.startsWith("http")) {
                url += "http://" + url;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            context.startActivity(intent);
        } catch (Exception e) {
            ZxToast.showINFOBottomToast("链接有误，请联系悬赏主更换正确链接！");
        }

    }

    /**
     * 启动发红包activity
     *
     * @param context
     * @param taskId
     */
    public static void startSendRedPackActivity(Context context, Integer taskId) {
        Intent intent = new Intent(context, SendRedPackActivity.class);
        intent.putExtra("taskId", taskId);
//        intent.putExtra("minMoney", minMoney);
        context.startActivity(intent);
    }

    /**
     * 启动红包详情页
     *
     * @param context
     * @param details
     */
    public static void startRedDetail(Context context, RedPackDetails details) {
        Intent intent = new Intent(context, RedPackDetailActivity.class);
        intent.putExtra("redPackDetails", details);
        context.startActivity(intent);
    }

    /**
     * 开始聊天界面
     *
     * @param context
     * @param id
     * @param name
     */
    public static void startChatActivity(Context context, String id, String name, int entrance, String extraData) {
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setType(V2TIMConversation.V2TIM_C2C);
        chatInfo.setId(id);
        chatInfo.setChatName(name);
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra(Conf.KEY_CHAT, chatInfo);
        intent.putExtra(Conf.KEY_ENTRANCE, entrance);
        intent.putExtra(Conf.KEY_EXTRA_DATA, extraData);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param id
     * @param name
     * @param entrance
     */
    public static void startChatActivity(Context context, String id, String name, int entrance) {
        startChatActivity(context, id, name, entrance, null);
    }

    /**
     * 添加计时器界面
     *
     * @param context
     * @param taskId
     * @param timerType
     */
    public static void startAddTimerActivity(Context context, Integer taskId, Integer timerType) {
        Intent intent = new Intent(context, TimerListActivity.class);
        intent.putExtra("taskId", taskId);
        intent.putExtra("timerType", timerType);
        context.startActivity(intent);
    }

    /**
     * 启动审核列表页
     *
     * @param context
     * @param managerTask
     */
    public static void startCheckListActivity(Context context, ManagerTask managerTask) {
        Intent intent = new Intent(context, TaskCheckListActivity.class);
        intent.putExtra("managerTask", managerTask);
        context.startActivity(intent);
    }

    /**
     * 从网络中保存文件到本地
     *
     * @param url
     * @param savePath
     */
    public static void saveFile(final String url, final String savePath, final Callback<Result<String>> callback) {
        Observable.create(new ObservableOnSubscribe<Result<String>>() {
            @Override
            public void subscribe(ObservableEmitter<Result<String>> e) throws Exception {
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), new TrustAllCerts())
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                Response response = okHttpClient.newCall(request).execute();
                File dir = new File(savePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, "" + ZxEncryptTool.encryptMD5ToString(url) + ZxFileTool.getUrlSuffix(url, ".png"));
                if (file.exists() && file.length() == response.body().contentLength()) {
                    Result<String> result = new Result<>();
                    result.setCode(201);
                    result.setData(file.getAbsolutePath());
                    result.setMessage("文件已存在");
                    ZxLogTool.i("save", "文件已存在。");
                    e.onNext(result);
                    return;
                }
                file.createNewFile();
                InputStream inputStream = response.body().byteStream();
                OutputStream outputStream = new FileOutputStream(file, false);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
                outputStream.close();

                Result<String> result = new Result<>();
                result.setCode(200);
                result.setData(file.getAbsolutePath());
                result.setMessage("保存成功");
                ZxLogTool.i("save", "保存成功。");
                e.onNext(result);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Result<String> s) {
                        callback.callback(s);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Result<String> result = new Result<>();
                        result.setCode(-1);
                        result.setData(null);
                        result.setMessage(e.getMessage());
                        callback.callback(result);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 通知图库更新相应图片
     *
     * @param context
     * @param file
     */
    public static void updateGallery(Context context, File file) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }


    /**
     * 保存分析图片
     *
     * @param bmp
     * @return
     */
    public static String saveShareBitmap(Bitmap bmp) {
        String filePath;
        try { // 获取SDCard指定目录下
            String sdCardDir = Conf.IMAGE_SAVE_PATH;
            File dirFile = new File(sdCardDir);  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }                          //文件夹有啦，就可以保存图片啦
            File file = new File(sdCardDir, "fenxiang.jpg");// 在SDcard的目录下创建图片文,以当前时间为其命名
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
//            System.out.println("_________保存到____sd______指定目录文件夹下____________________");
            //LogTool.LogE("saveBitMap", "saveBitmap: 图片保存到" + Environment.getExternalStorageDirectory() + "/zupubao/" + bitmapName);
            filePath = Conf.IMAGE_SAVE_PATH + "fenxiang.jpg";
//            showShare(QQFilePath);
            out.flush();
            out.close();
//            if (insertPhotoAlbum)
//                Tool.insertPhotoAlbum(filePath, "fenxiang.jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePath;
//        Toast.makeText(HahItemActivity.this,"保存已经至"+Environment.getExternalStorageDirectory()+"/CoolImage/"+"目录文件夹下", Toast.LENGTH_SHORT).show();
    }

    /**
     * 解析二维码
     *
     * @param path
     * @param result
     */
    public static void parseQRCode(final String path, final Callback<String> result) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                // 解析二维码/条码
//                String result = QRCodeDecoder.syncDecodeQRCode(path);
                String result = CodeUtils.parseQRCode(path);
                // 要做判空，不然可能会报空指针异常
                result = (null == result) ? "" : result;
                e.onNext(result);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        result.callback(s);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 获取图片选择的配置
     *
     * @param activity
     * @return
     */
    public static PictureSelectionModel getPictureSelector(Activity activity, int maxNum) {
        int selectionMode = PictureConfig.MULTIPLE;
        if (maxNum == 1) {
            selectionMode = PictureConfig.SINGLE;
        }
        return PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(selectionMode)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(false)// 是否可预览视频
                .enablePreviewAudio(false) // 是否可播放音频
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .compressSavePath(getPath())//压缩图片保存地址
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(16, 9)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .isGif(true)// 是否显示gif图片
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
//                .selectionMedia(selected)// 是否传入已选图片
                //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                .cropCompressQuality(50)// 裁剪压缩质量 默认100
                .minimumCompressSize(100);// 小于100kb的图片不压缩
        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
        //.rotateEnabled(true) // 裁剪是否可旋转图片
        //.scaleEnabled(true)// 裁剪是否可放大缩小图片
        //.videoQuality()// 视频录制质量 0 or 1
        //.videoSecond()//显示多少秒以内的视频or音频也可适用
        //.recordVideoSecond()//录制视频秒数 默认60s
//                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * 图片选择完成后发送消息
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public static void PictureSelectedSuccessSendMsg(int requestCode, int resultCode, Intent data) {
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == Activity.RESULT_OK) {
            EventBus.getDefault().post(new EventMsg(EventMsg.IMAGE_SELECTED_SUCCESS,
                    data.getSerializableExtra(PictureConfig.EXTRA_RESULT_SELECTION)));
        }
    }

    /**
     * 开始提现
     *
     * @param context
     * @param type    1赚取金2充值金3保证金
     */
    public static void startWithdrawalActivity(Context context, int type) {
        Intent intent = new Intent(context, WithdrawalActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param type    订单资金目标：2、充值金；3、保证金；4、VIP充值
     * @param money   充值数额
     * @param isBack  充值完成后是否返回
     */
    public static void startRechargeActivity(Context context, int type, String money, boolean isBack) {
        Intent intent = new Intent(context, RechargeActivity.class);
        intent.putExtra("money", money);
        intent.putExtra("target", type);
        intent.putExtra("isBack", isBack);
        context.startActivity(intent);
    }

    /**
     * 进入用户信息界面
     *
     * @param context
     * @param userId
     */
    public static void startUserInfoActivity(Context context, Integer userId) {
        Intent intent = new Intent(context, UserInfoActivity.class);
        intent.putExtra("userId", userId);
        context.startActivity(intent);
    }


    /**
     * 规则弹窗
     *
     * @param activity
     * @param view
     */
    public static void showPopupRules(Activity activity, View view) {
        PopMenuAdapter popMenuAdapter = new PopMenuAdapter() {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view1 = super.getView(position, convertView, parent);
                LinearLayout v = (LinearLayout) ((RelativeLayout) view1).getChildAt(0);
                v.getLayoutParams().height = 30 * ResManager.dp();
                TextView textView = view1.findViewById(com.tencent.qcloud.tim.uikit.R.id.pop_menu_label);
                textView.setGravity(Gravity.CENTER);
                textView.setTextSize(12);
                return view1;
            }
        };
        QMUIListPopup popup = new QMUIListPopup(activity, QMUIPopup.DIRECTION_NONE, popMenuAdapter);
        popup.create(ResManager.dp() * 80, ResManager.dp() * 120, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        ZxActivityTool.skipActivity(activity, RulePublishActivity.class);
                        break;
                    case 1:
                        ZxActivityTool.skipActivity(activity, RuleOrderActivity.class);
                        break;
                    case 2:
                        ZxActivityTool.skipActivity(activity, RuleReportActivity.class);
                        break;
                    case 3:
                        ZxActivityTool.skipActivity(activity, RulePunishmentActivity.class);
                        break;
                    case 4:
                        ZxActivityTool.skipActivity(activity, RuleReputationActivity.class);
                        break;
                }
                popup.dismiss();
            }
        });
        List<PopMenuAction> actions = new ArrayList<>();
        PopMenuAction action = new PopMenuAction();
        action.setActionName("发布规则");
        actions.add(action);
        action = new PopMenuAction();
        action.setActionName("接单规则");
        actions.add(action);
        action = new PopMenuAction();
        action.setActionName("举报规则");
        actions.add(action);
        action = new PopMenuAction();
        action.setActionName("惩罚规则");
        actions.add(action);
        action = new PopMenuAction();
        action.setActionName("信誉规则");
        actions.add(action);

        popMenuAdapter.setDataSource(actions);
        popup.show(view);
    }

    /**
     * 得到升级需要的积分
     *
     * @param current
     * @return 当前积分
     */
    public static int getMaxScore(int current) {
        if (current < 1)
            return 1;
        if (current < 100) {
            return 100;
        }
        if (current < 1000) {
            return 1000;
        }
        if (current < 2000)
            return 2000;
        if (current < 10000) {
            return 10000;
        }
        if (current < 50000) {
            return 50000;
        }
        if (current < 100000) {
            return 100000;
        } else {
            return 999999;
        }
    }

    /**
     * 实体类转Map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                if (o != null) {
                    map.put(field.getName(), o);
                }
                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 压缩图片
     *
     * @param file 压缩前的图片
     * @return 返回一个压缩后的临时文件图片
     * @throws Exception
     */
    public static File compressImage(File file, boolean isWatermark) throws Exception {
        String suffix = ".png";
        if (file.exists()) {
            suffix = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf('.'));
        }
        Bitmap b = null;
        //压缩图片
        b = ZxImageUpload.getCompressBitmap(file.getAbsolutePath());
        if (isWatermark) {
            //给图片加水印
            b = ZxImageTool.createWaterMaskRightBottom(ZxTool.getContext(), b,
                    BitmapFactory.decodeResource(App.getInstance().getResources(), R.mipmap.watermark),
                    5, 5);
            //生成文字水印
            Bitmap text = createWatermark(b.getWidth(), b.getHeight(), "悬赏示例图");
            //合成
            Bitmap newb = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(newb);
            canvas.drawBitmap(b, 0, 0, null);
            canvas.drawBitmap(text, 0, 0, null);
            b.recycle();
            text.recycle();
            b = newb;
        }
        //将压缩后的图片保存
        File img = File.createTempFile(ZxTimeTool.getCurrentDateTime("yyyyMMdd")+"_" +ZxDataTool.getRandomString(5)+"_", suffix);
        ZxFileTool.writeBitmapToSD(img.getPath(), b, true);
        //如果压缩后还大于1M，那就再压缩一次！
        if (img.length() > 1024 * 1024 * 1) {
            b = ZxImageUpload.getCompressBitmap(img.getAbsolutePath());
            ZxFileTool.writeBitmapToSD(img.getPath(), b, true);
        }
        if (b != null && !b.isRecycled()) {
            b.recycle();
        }
        return img;
    }


    /**
     * 得到一个去掉末尾0的BigDecimal
     *
     * @param dec
     * @return
     */
    public static BigDecimal getPrettyNumber(BigDecimal dec) {
        if (dec == null) return new BigDecimal(0);
        BigDecimal decimal = new BigDecimal(dec.stripTrailingZeros().toPlainString());
        return decimal;
    }

    /**
     * 使editView得到焦点
     *
     * @param context
     * @param editText
     */
    public static void requestFocus(Context context, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        ZxTool.openKeybord(editText, context);
    }


    /**
     * 画两个斜着的水印图
     *
     * @param w
     * @param h
     * @param text
     * @return
     */
    public static Bitmap createWatermark(int w, int h, String text) {
        int fontsize = w / 7;
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(0x0);
        Paint paint = new Paint();
        paint.setColor(0x66AAAAAA);
//        paint.setAlpha(50);
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setTextSize(fontsize);
        //画第一个水印
        canvas.save();
        canvas.translate(w / 8, h / 2);
        canvas.rotate(-45);
        canvas.drawText(text, 0, 0, paint);
        canvas.restore();
        //画第二个水印
        canvas.save();
        canvas.translate(w / 3, h / 1.3f);
        canvas.rotate(-45);
        canvas.drawText(text, 0, 0, paint);
        canvas.restore();

        return bitmap;
    }


    /**
     * 提示弹窗
     *
     * @param context
     * @param tips
     */
    public static void showTips(Context context, CharSequence tips) {
        TipsDialog tipsDialog = new TipsDialog(context);
        tipsDialog.setTitle("提示");
        tipsDialog.setContent(tips);
        tipsDialog.setSubmitText("好的");
        tipsDialog.setContentGravity(Gravity.CENTER);
        tipsDialog.setCanceledOnTouchOutside(true);
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }


    /**
     * 发送任务消息
     *
     * @param context 上下文对象
     * @param task    任务对象
     * @param type    1直接发送 2发送第一条消息后发送
     */
    public static void sendTaskMsg(Context context, String userId, Task task, int type) {
        int entrance = 0;
        if (type == 1) {
            entrance = 6;
        } else if (type == 2) {
            entrance = 1;
        }
        Tool.startChatActivity(context, "" + userId, userId, entrance,
                new StringBuilder("jb://task?id=")
                        .append(task.getId())
                        .append("&title=")
                        .append(ZxEncodeTool.urlEncode(task.getTitle()))
                        .append("&depict=")
                        .append(ZxEncodeTool.urlEncode(task.getRemark()))
                        .append("&icon=")
                        .append(ZxEncodeTool.urlEncode(task.getAvatar()))
                        .toString()
        );
    }


}